package com.chen.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.common.Result;
import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.pojo.bean.UserInfo;
import com.chen.service.LoginService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Service
@SuppressWarnings("all")
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {
    private static Map<String,UserInfo> cacheMap = new ConcurrentHashMap<>();
    private static Map<String,Long> cacheToken = new ConcurrentHashMap<>();



    @Resource
    UserMapper userMapper;

    //登录
    @Override
    public Result login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        queryWrapper.eq("password", user.getPassword());
        User res = userMapper.selectOne(queryWrapper);
        if (res == null) {
            return Result.error(50001, "用户名或密码错误");
        }
        UserInfo info = new UserInfo(res);
        String token = IdUtil.simpleUUID();
        Long tokenTime = System.currentTimeMillis();
        cacheMap.put(token, info);
        cacheToken.put(token,tokenTime);
        Map<String,String> resMap = new HashMap<>();
        resMap.put("token",token);
        return Result.success(resMap);

    }

    @Override
    public Result<?> register(User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null) {
            return Result.error(-1, "该用户以存在");
        }
        if (user.getPassword()==null){
            user.setPassword("123456");
        }

        return null;
    }

    @Override
    public Result<?> forget(User user) {
        return null;
    }

    @Override
    public Result<?> reset(User user) {
        return null;
    }

    @Override
    public Result<?> info(String token) {
        try {
            Long historyTime = cacheToken.get(token);
            Long nowTime = System.currentTimeMillis();
            if (nowTime - historyTime > 1800000L) {
                cacheToken.remove(token);
                cacheMap.remove(token);
                return Result.error(20001,"Token已经失效，请重新登录。");
            } else {
                UserInfo info = cacheMap.get(token);
                cacheToken.put(token,nowTime);
                return Result.success(info);
            }
        } catch (Exception e) {
            log.error("[info] some error = {}", e.getMessage());
            return Result.error(20001,"Token已经失效，请重新登录。");
        }
    }
}
